import 'dart:math';

import 'package:dio/dio.dart';

import '../../page/login/state.dart';

class NetRequestInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    Map map = options.method == 'GET' ? options.queryParameters : options.data;

    String ctimestamp =
        (DateTime.now().millisecondsSinceEpoch / 1000).toInt().toString();
    String papams = '';
    String cnonce = randomString(6);
    if (map.length > 0) {
      papams = map.values.toList()[0].toString();
    }

    String cData = '${papams}-POST-${ctimestamp}-${cnonce}';

    // SM3Digest().
    // StreamCipher('SM3')
    // MethodChannelManager.platform
    //     .invokeMethod('sm3EncryptText', cData)
    //     .then((csign) {
    options.headers = {
      "appCode": "jx-clivil-servant-assessment",
      "userId": PasswordloginState.userinfo != null
          ? PasswordloginState.userinfo!.userId
          : '',
      "token": PasswordloginState.userinfo != null
          ? PasswordloginState.userinfo!.token
          : '',
      "userName": PasswordloginState.userinfo != null
          ? Uri.encodeComponent(
              PasswordloginState.userinfo!.userName.toString())
          : '',
      "organId": PasswordloginState.userinfo != null
          ? PasswordloginState.userinfo!.loginPostInfo!.orgId
          : '',
      "tenantId": PasswordloginState.userinfo != null
          ? PasswordloginState.userinfo!.tenantId!
          : '',
      "type": 1,
      "ctimestamp": ctimestamp,
      "cnonce": cnonce,
      // "csign": csign  VeraWong_ww
    };

    print('---header---' + options.headers.toString());
    return handler.next(options); //continue
  }

  String randomString(int len) {
    String charsAll = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = charsAll.length;
    var pwd = '';
    for (int i = 0; i < len; i++) {
      pwd += charsAll[Random().nextInt(maxPos)];
    }
    return pwd;
  }
}
